/*
 * @Description: 权限控制
 * @Author: wangfuwei
 * @Date: 2020-12-22 15:17:24
 * @LastEditors: wangfuwei
 * @LastEditTime: 2021-04-24 16:00:37
 * @FilePath: /horizon-frontend/src/core/permission.js
 */
import Vue from "vue";
import router from "@/router";
import store from "@/store";

import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { LOGIN_PATH, ACCESS_TOKEN } from "@/core/const";

NProgress.configure({ showSpinner: false });

const whiteList = [LOGIN_PATH]; // 白名单

/**
 * @description: 路由前置处理
 * @param {*}
 * @return {*}
 */
router.beforeEach((to, from, next) => {
  NProgress.start();

  if (Vue.ls.get(ACCESS_TOKEN)) {
    //LS存在token即登录过

    //登录页面直接进入首页
    if (to.path === LOGIN_PATH) {
      next({ path: "/" });
      return;
    }

    //进入首页或应用页面
    if (store.state.user.username) {
      const appMaps = store.state.menu.appMaps;
      let appCode = to.path.split("/")[1];
      if (Object.keys(appMaps).includes(appCode)) store.dispatch("menu/active", { appCode }).then(() => next());
      else next();
      return;
    }

    //获取用户基本信息和拥有权限的云应用
    Promise.all([store.dispatch("user/getInfo"), store.dispatch("menu/getCloudApps")])
      .then(() => {
        window.vm.$welcome.show(); //欢迎页面

        const appMaps = store.state.menu.appMaps;
        let appCode = to.path.split("/")[1];
        let redirect = to.redirectedFrom === "/" || from.query.redirect === "/index" ? decodeURIComponent(to.fullPath) : decodeURIComponent(from.query.redirect || to.fullPath);
        if (to.fullPath !== redirect) {
          const pathname = redirect.includes("?") ? redirect.split("?")[0] : redirect;
          appCode = pathname.split("/")[1];
        }
        if (Object.keys(appMaps).includes(appCode)) {
          store.dispatch("menu/active", { appCode }).then(() => next({ path: toPath(redirect), replace: decodeURIComponent(to.fullPath) === redirect }));
        } else {
          next({ path: toPath(redirect), replace: decodeURIComponent(to.fullPath) === redirect });
        }
      })
      .catch(error => {
        //Token失效，自动退出
        store.dispatch("user/logout").then(() => next({ path: LOGIN_PATH, query: to.path === "/index" ? {} : { redirect: to.fullPath } }));
        throw error;
      });

    return;
  }

  // 不存在token即未登录
  // 免登录白名单
  if (whiteList.includes(to.path)) next();
  //跳转登录页面并保存页面地址
  else next({ path: LOGIN_PATH, query: to.path === "/index" ? {} : { redirect: to.fullPath } });
});

/**
 * @description: 路由后置处理
 * @param {*}
 * @return {*}
 */
router.afterEach(to => {
  if (to.matched.length === 0) router.push("/403");
  NProgress.done();
});

/**
 * @description: 获取登录成功后跳转地址，若存在redirect，则跳转redirect
 * @param {String} path 原始redirect地址
 * @return {String} 登录成功后跳转地址
 */
function toPath(path) {
  const idx = path.indexOf("redirect=");
  if (idx !== -1) path = path.substring(idx + 9);
  return path;
}
